<template>
  <div class="login">
    <van-nav-bar title="登录"
                 left-arrow
                 @click-left="$router.back()" />
    <van-form @submit="loginFn">
      <van-field v-model="mobile"
                 label="手机号"
                 placeholder="请输入手机号"
                 :rules="rules.mobile"
                 required />
      <van-field v-model="code"
                 label="验证码"
                 placeholder="请输入验证码"
                 :rules="rules.code"
                 required />
      <div style="margin: 16px;">
        <van-button round
                    block
                    type="info"
                    native-type="submit"
                    loading-text="登录中..."
                    :disabled="isLoading"
                    :loading="isLoading">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { login } from '@/api/user'
// import request from '@/utils/request'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '17383875406',
      code: '246810',
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          }, {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }

        ]

      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async loginFn() {
      this.isLoading = true
      try {
        const res = await login(this.mobile, this.code)
        // console.log(res)
        this.$store.commit('user/setToken', res.data)
        if (this.$route.query.goBack) {
          return this.$router.back()
        }
        const back = this.$route.query.back || '/'
        this.$router.push(back)
        this.$toast.success('登陆成功')
        // 成功跳转去首页
      } catch {
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }

}
</script>

<style lang="scss" scoped>
</style>
